package top.continew.admin.generator.controller;

import top.continew.admin.generator.service.impl.ImportBatchServiceImpl;
import top.continew.admin.generator.service.impl.TaskListServiceImpl;
import top.continew.starter.extension.crud.enums.Api;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.*;
import top.continew.starter.web.model.R;
import top.continew.starter.extension.crud.annotation.CrudRequestMapping;
import top.continew.admin.common.controller.BaseController;
import top.continew.admin.generator.model.query.ImportBatchQuery;
import top.continew.admin.generator.model.req.ImportBatchReq;
import top.continew.admin.generator.model.resp.ImportBatchDetailResp;
import top.continew.admin.generator.model.resp.ImportBatchResp;
import top.continew.admin.generator.service.ImportBatchService;
import top.continew.admin.generator.service.TaskListService;
import top.continew.admin.generator.service.TaskAssignmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import top.continew.admin.generator.model.entity.TaskListDO;
import top.continew.admin.generator.model.entity.TaskAssignmentDO;
import lombok.RequiredArgsConstructor;

/**
 * 导入批次管理 API
 *
 * @author jiangjun
 * @since 2025/01/20 10:00
 */
@Tag(name = "导入批次管理 API")
@RestController
@RequiredArgsConstructor
@CrudRequestMapping(value = "/generator/importBatch", api = {Api.PAGE, Api.GET, Api.DELETE})
public class ImportBatchController extends BaseController<ImportBatchService, ImportBatchResp, ImportBatchDetailResp, ImportBatchQuery, ImportBatchReq> {

    private final TaskListService taskListService;
    private final TaskAssignmentService taskAssignmentService;

    @Operation(summary = "删除批次及关联明细")
    @DeleteMapping("/{id}/cascade")
    public R<Void> deleteCascade(@PathVariable String id) {
        // 先删除批次关联的任务分配
        LambdaQueryWrapper<TaskAssignmentDO> assignmentWrapper = new LambdaQueryWrapper<>();
        assignmentWrapper.eq(TaskAssignmentDO::getBatchId, id);
        taskAssignmentService.remove(assignmentWrapper);
        
        // 再删除批次关联的任务明细
        LambdaQueryWrapper<TaskListDO> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(TaskListDO::getBatchId, id);
        ((TaskListServiceImpl) taskListService).remove(taskWrapper);
        
        // 最后删除批次记录
        ((ImportBatchServiceImpl) baseService).removeById(id);
        return R.ok();
    }
}